package cn.assumejson.springframework.beans.factory.support;

import cn.assumejson.springframework.beans.factory.BeanFactory;
import cn.assumejson.springframework.beans.factory.BeansException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * JDK实现
 *
 * @author Mr. Li
 * @version 1.0
 * @since 1.0 2021/11/30 8:47
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName) throws ClassNotFoundException {
        return instantiate(bd, beanName, null);
    }

    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName, Constructor<?> ctor, Object... args) throws ClassNotFoundException {
        Class<?> beanClass = bd.getBeanClass();
        try {
            if (null != ctor) {
                return beanClass.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            } else {
                return beanClass.getDeclaredConstructor().newInstance();
            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new BeansException("Failed to instantiate [" + beanClass.getName() + "]", e);
        }
    }
}
